package com.zr.task.activity;

import android.app.Dialog;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zh.baselibrary.base.BaseNoIMActivity;
import com.zh.baselibrary.base.BasePresenter;
import com.zh.baselibrary.base.BaseRecyclerAdapter;
import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.utils.ClickUtils;
import com.zh.baselibrary.utils.ComparatorUtils;
import com.zh.baselibrary.utils.IntentUtils;
import com.zh.baselibrary.utils.JsonUtils;
import com.zh.baselibrary.utils.ListUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.task.home.CabinetBean;
import com.zh.model.task.home.ClassCabinetBean;
import com.zh.model.task.home.CommitBean;
import com.zr.andealib.util.HardEvent;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.task.R;
import com.zr.task.adapter.EmergencyCabinetAdapter;
import com.zr.task.adapter.GridSpacingItemDecoration;
import com.zr.task.dialog.ChooseDialog;
import com.zr.task.presenter.EmergencyPresenter;
import com.zr.task.presenter.view.EmergencyView;
import com.zr.task.utils.EquipmentTypeUtils;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;

import butterknife.BindView;
import butterknife.OnClick;

public class EmergencyActivity extends BaseNoIMActivity<EmergencyPresenter> implements BaseRecyclerAdapter.OnItemClickListener, EmergencyView {

    @BindView(R.id.tv_name)
    TextView tv_Name;
    @BindView(R.id.ry_cabinet)
    RecyclerView mRyCabinet;
    @BindView(R.id.out)
    Button bt_Out;

    EmergencyCabinetAdapter mAdapter;
    ClassCabinetBean cabinetBean;
    CountDownTimer countTimer;


    private static final Long MILLISINFUTURE = (long) 121 * 1000;
    private static final Long COUNTDOWNINTERVAL = (long) 1000;
    private int hostPosition = 0;



    @Override
    protected int getLayoutId() {
        return R.layout.activity_emergency;
    }

    @Override
    protected void init() {
        cabinetBean = JsonUtils.stringToObject(ShareManager.getValue(this, BaseConstant.LOCAL_CAB_LIST), ClassCabinetBean.class);

        int count = EquipmentTypeUtils.getBoxNum(this);
        int spanCount = (count + 1) / 3;
        mRyCabinet.setLayoutManager(new GridLayoutManager(this, spanCount));
        mRyCabinet.addItemDecoration(new GridSpacingItemDecoration(spanCount, 20, false));
        Collections.sort(cabinetBean.getCabinetDetailList(), new ComparatorUtils("", "cabinetNum", true));
        if(cabinetBean.getCabinetDetailList().size()>0) {
            int first = cabinetBean.getCabinetDetailList().get(0).getCabinetNum();
            int cha = first - 1;
            for (int k = 0; k < cha; k++) {
                cabinetBean.getCabinetDetailList().add(0,null);
            }
        }
        if (count <= 2)
            hostPosition = 0;
        else
            hostPosition = 1;
        cabinetBean.getCabinetDetailList().add(hostPosition, null);
        mAdapter = new EmergencyCabinetAdapter(compliteData(hostPosition,cabinetBean.getCabinetDetailList()));
        mAdapter.setCount(count + 1); //设置adapter数量
        mAdapter.setOnItemClickListener(this);
        mRyCabinet.setAdapter(mAdapter);
        tv_Name.setText((getIntent().getStringExtra(ExtraName.KEY_DATA) + "老师，您好！"));
        countTimer = new CountDownTimer(MILLISINFUTURE, COUNTDOWNINTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                bt_Out.setText(("退出登录" + millisUntilFinished / 1000 + "s"));
            }

            @Override
            public void onFinish() {
                startActivity();
            }
        };
        countTimer.start();
        EventBus.getDefault().register(this);
        bt_Out.post(new Runnable() {
            @Override
            public void run() {
                mPresenter.canOut();
            }
        });

    }
    public List<CabinetBean> compliteData(int host ,List<CabinetBean> list) {
        if (ListUtils.isEmpty(list))
            return list;
        List<CabinetBean> item = new ArrayList<>();
        int j = 1;
        int length = list.size();
        for (int i = 0; i < length; i++) {
            if (list.get(i) == null) {
                item.add(null);
                if(i!=host)
                    j++;
            } else {
                if (list.get(i).getCabinetNum() == j) {
                    item.add(list.get(i));
                    j++;
                } else if (list.get(i).getCabinetNum() > j) {
                    int cha = list.get(i).getCabinetNum() - j;
                    for (int k = 0; k < cha; k++) {
                        item.add(null);
                        j++;
                    }
                    i--;
                }
            }
        }
        return item;
    }
    @Override
    protected EmergencyPresenter createPresenter() {
        return new EmergencyPresenter();
    }

    @OnClick({R.id.out, R.id.iv_back})
    public void onClick(View view) {
        if(ClickUtils.isFastClick()) {
            if (mPresenter.canOut())
                new ChooseDialog(this, R.style.DialogTheme, "确认退出登录？", new ChooseDialog.OnClickListener() {
                    @Override
                    public void onClick(View view, Dialog dialog) {
                        startActivity();
                    }
                }).show();
            else
                ToastView.showLong("请先关闭柜门");
        }
    }

    private void startActivity() {
        countTimer.cancel();
        IntentUtils.instance().startActivity(this, TaskMainActivity.class);
    }

    @Override
    public void onItemClick(View v, int position) {
        if (position != hostPosition) {
            if(ClickUtils.isFastClick()) {
               v.setEnabled(false);
                mPresenter.toOpenUi(position);
            }
        }
    }

    @Subscribe(priority = 1000,threadMode = ThreadMode.POSTING)
    public void Event(HardEvent hardEvent) {
        int flag = hardEvent.getFlag();
        if (flag == AndeaConstant.CALL_LOCK_STATUS_SUCCSES) {
            mPresenter.checkDoorClose((Integer) hardEvent.getData());
            EventBus.getDefault().cancelEventDelivery(hardEvent) ;
        }else if(flag == AndeaConstant.CALL_LOCK_STATUS_ERROR ){
            String tip = (String)hardEvent.getData();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastView.showLong(tip);
                }
            });
            EventBus.getDefault().cancelEventDelivery(hardEvent) ;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void doorClosed(int boxNum,int uiNum) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastView.showLong("作业已全部取出");
                mRyCabinet.findViewHolderForAdapterPosition(uiNum).itemView.setEnabled(true);
                EventBus.getDefault().post(new HardEvent(boxNum,AndeaConstant.CALL_EMERGENCY));
            }
        });
    }

    @Override
    public void notClosedBefore(int uiNum,boolean canClick) {
        mRyCabinet.findViewHolderForAdapterPosition(uiNum).itemView.setEnabled(false);
    }
}
